package ws.very.util.lang

import java.util.HashMap

import ws.very.util.lang.ShortTypes._
object WhenShutDown {
  def apply(r: => Unit) = ShutDownAction + (r)
}

object ShutDownAction extends ThreadConverter {
  private var token = 0
  private val map = new HashMap[I, Thread]
  def +(r: => Unit): I = {
    val thread = r: Thread
    this.synchronized {
      val t = token
      map.put(t, thread)
      this + (thread)
      token = token + 1
      t
    }
  }
  def +(r: Thread) = {
    Runtime.getRuntime.addShutdownHook(r)
    r
  }
  def -(action: Thread): B = Runtime.getRuntime.removeShutdownHook(action)

  def -(token: I): B = this.synchronized {
    O(map.get(token)).map { thread =>
      this - map.remove(token)
    }.getOrElse(false)
  }

  def size = map.size()
}